package com.saascloud.core.saas;

import com.saascloud.Constants;
import com.saascloud.thread.ThreadTaskUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

import java.util.UUID;


/**
 * @Author: liangxu
 * @Contact: one_dream@aliyun.com
 * @Date: 2022/5/13 9:20
 * @Version: 1.0
 * @Description: saas化租户信息上下文工具，用于上下问信息传递，具体传递内容见
 * com.saascloud.common.core.saas.SaasContextUtil.TenantObj
 */
@Slf4j
public class SaasContextUtil {

    public static ThreadLocal<TenantObj> tenantIdLocal = ThreadTaskUtils.newThreadLocal(TenantObj::new);

    public static String getTenantId() {
        return get().getTenantId();
    }

    public static void setTenantId(String tenantId) {
        get().setTenantId(tenantId);
    }

    public static void setTraceId(String traceId) {
        if (!StringUtils.hasLength(traceId)) {
            MDC.put(Constants.Trace.TRACE_KEY, UUID.randomUUID().toString());
        } else {
            MDC.put(Constants.Trace.TRACE_KEY, traceId);
        }
        get().setTraceId(traceId);

    }

    public static String getTraceId() {
        return get().getTraceId();
    }

    public static String getToken() {
        return get().getToken();
    }

    public static void setToken(String token) {
        get().setToken(token);
    }

    private static TenantObj get() {
        return tenantIdLocal.get();
    }


    public static void remove() {
        tenantIdLocal.remove();
        MDC.remove(Constants.Trace.TRACE_KEY);
    }

    /**
     * saas化租户信息对象
     */
    private static class TenantObj {
        /**
         * 租户id
         */
        private String tenantId;

        /**
         * 请求token
         */
        private String token;

        /**
         * traceId,和MDC有关系
         */
        private String traceId;

        public String getTenantId() {
            return tenantId;
        }

        public void setTenantId(String tenantId) {
            this.tenantId = tenantId;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }

        public String getTraceId() {
            return traceId;
        }

        public void setTraceId(String traceId) {
            this.traceId = traceId;
        }
    }

    public static void main(String[] args) {
        System.out.println(SaasContextUtil.getTenantId());
        SaasContextUtil.setTenantId("aa");
        System.out.println(SaasContextUtil.getTenantId());
        SaasContextUtil.remove();
        System.out.println(SaasContextUtil.getTenantId());

    }


}
